package com.zr.domain.sp.tool.zk;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

//@Service
public class DistributedLockService {

    @Autowired
    private CuratorFramework curatorFramework;

    public void lockAndDoSomething() {
        InterProcessMutex lock = new InterProcessMutex(curatorFramework, "/my_lock");
        try {
            lock.acquire();
            // 在这里执行需要同步的代码
            System.out.println("Doing something with exclusive access");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (lock.isAcquiredInThisProcess()) {
                    lock.release();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

